<?php
namespace app\admin\controller;

use app\common\helper\Cookie;
use think\Cache;
use think\Db;
use think\Request;
use think\Session;

class Site extends Common
{

    /**
     * 登录
     */
    public function login(){
        $this->view->engine->layout('common/iframe');
        if(Request::instance()->isAjax()){
            try {
                $input = input("request.",'','trim');
                $validate = $this->validate($input, 'User.login');
                if($validate !== true){
                    exception($validate);
                }

                $name = $input["name"];
                $password = $input["password"];
                $is_remember = isset($input["remember"]);
                Db::startTrans();
                $user = Db::name('user')->where(['mobile|name'=>$name])->find();
                if(empty($user)){
                    exception('账号不存在');
                }
                if($user['password'] != md5($password)){
                    exception('账号密码错误');
                }
                if($user["status"] == 2){
                    exception('账号已冻结');
                }
                if($is_remember){
                    Cookie::setCookie('password',$password);
                    \cookie('mobile',$name);
                }else{
                    cookie('mobile', null);
                    cookie('password', null);
                }
                unset($user["password"]);
                session('user_id',$user["id"]);
                session('user',$user);
                Db::commit();
                return ["code" => 0, "msg" =>'登录成功','url'=>url('/admin/index/index'),'data'=>$user];
            } catch (\Exception $exception) {
                Db::rollback();
                return ["code" => 1, "msg" =>$exception->getMessage(),'data'=>[]];
            }
        }
        return view('login',['mobile'=>\think\Cookie::get('mobile'),'password'=>Cookie::getCookie('password')]);
    }



    /**
     * 修改密码
     */
    function changePassword(){
        if(Request::instance()->isPost()){
            try{
                Db::startTrans();
                $data = input('post.','','trim');
                $validate = $this->validate($data, 'User.changePassword');
                if ($validate !== true) {
                    exception($validate);
                }
                $user = \app\common\model\User::where(['id'=>$this->userId])->find();
                if($user['password'] != md5($data['oldpassword'])){
                    exception('原密码错误');
                }
                if($user->force()->update(['id'=>$user->id,'password'=>md5($data['password'])]) === false){
                    exception('修改失败');
                };
                Db::commit();
                return ['code'=>0,'msg'=>'修改成功'];
            } catch (\Exception $e) {
                Db::rollback();
                return ["code" => 1, "msg" =>$e->getMessage(),'data'=>[]];
            }
        }
        return view();
    }



    /**
     * 忘记密码
     */
    function forget(){
        $this->view->engine->layout('common/iframe');
        if(Request::instance()->isPost()){
            try {
                Db::startTrans();
                $input = input('post.',null,'trim');

                $validate = $this->validate($input, 'user.forget');
                if ($validate !== true) {
                    exception($validate);
                }
                $user = \app\common\model\User::get(['mobile'=>$input['mobile']]);
                if(empty($user)){
                    exception('账号不存在');
                }
                if($user["status"] == 2){
                    exception('账号已冻结');
                }
                $input['id'] = $user['id'];

                $validate_code = SendCode::validateMobileCode($input['mobile'],$input['code']);
                if($validate_code['code'] == 0){
                   exception($validate_code['msg']);
                }
                $input['password'] = md5($input['password']);
                unset($input['code']);
                unset($input['repassword']);
                if($user->force()->update($input) === false){
                    exception('保存失败');
                };
                Cache::rm('sms_code_'.$input['mobile']);
                Db::commit();
                return json(['code'=>0,'msg'=>'修改成功']);
            }catch (\Exception $e){
                Db::rollback();
                return ['code'=>1,'msg'=>$e->getMessage()];
            }
        }
        return view();
    }



    /**
     * 修改账号
     */
    function changeAccount(){
        if(Request::instance()->isPost()){
            try{
                Db::startTrans();
                $data = input('post.','','trim');
                $validate = $this->validate($data, 'User.check');
                if ($validate !== true) {
                    exception($validate);
                }
                $user = \app\common\model\User::where(['id'=>$this->userId])->find();
                if($user->force()->update(['id'=>$user->id,'name'=>$data['name'],'mobile'=>$data['mobile'],'email'=>$data['email']]) === false){
                    exception('修改失败');
                };

                Db::commit();
                return ['code'=>0,'msg'=>'修改成功'];
            } catch (\Exception $e) {
                Db::rollback();
                return ["code" => 1, "msg" =>$e->getMessage(),'data'=>[]];
            }
        }
        return view();
    }


    /**
     * 退出
     */
    function logout()
    {
        Session::clear();
        $this->redirect(url('/admin/site/login'));
    }
}
